package org.tarena.dang.action.order;

import java.sql.SQLException;

import org.tarena.dang.action.BaseAction;
import org.tarena.dang.entity.CartItem;
import org.tarena.dang.entity.User;
import org.tarena.dang.entity.UserAdress;
import org.tarena.dang.service.CartFactory;
import org.tarena.dang.service.CartService;
import org.tarena.dang.service.OrderService;
import org.tarena.dang.service.OrderServiceImp;
import org.tarena.dang.util.Constant;

public class AddressAction extends BaseAction {
	private UserAdress address;
	private int addressId;
	private int orderId;
	private double totalPricae;
	public String execute(){
//			String add = new String(addressId+"");
//			add = add.split("/")[0];
//			addressId = Integer.parseInt(add);
			System.out.println("****&&**&**&&&&&&"+addressId);
			System.out.println("收货地址=="+address.getFullAddress());
			OrderService orderService = new OrderServiceImp();
			CartService cartService = CartFactory.getCart(session);
			totalPricae = cartService.count();
			User user = (User)session.get(Constant.USER);
			int n =0;//新地址标示位
			if(user!=null){
				try {
					System.out.println("***"+user.getId());
					if(addressId==0){
						if(orderService.insertAdd(user.getId(),address)){
							orderId = orderService.saveOrder(user.getId(),address,cartService.count(),Constant.WAIT_PAY,System.currentTimeMillis());
							if(orderId!=0){
								for(CartItem c:cartService.getBuyList()){
									 n += orderService.saveItems(orderId,c);
								}
								if(n==cartService.getBuyList().size()){
									session.remove(Constant.CART);
									 return "success"; 
								 }
								
							}
							
						}
					}else{
						orderId = orderService.saveOrder(user.getId(),address,cartService.count(),Constant.WAIT_PAY,System.currentTimeMillis());
						if(orderId!=0){
							for(CartItem c:cartService.getBuyList()){
								 n += orderService.saveItems(orderId,c);
							}
							if(n==cartService.getBuyList().size()){
								session.remove(Constant.CART);
								 return "success"; 
							 }
							
						}
					}
					
				} catch (SQLException e) {
					System.out.println("数据库操作出错！");
					e.printStackTrace();
					return "error";
				}
			}
		
		
		return "error";
	}
	public UserAdress getAddress() {
		return address;
	}
	public void setAddress(UserAdress address) {
		this.address = address;
	}
	public int getOrderId() {
		return orderId;
	}
	public void setOrderId(int orderId) {
		this.orderId = orderId;
	}
	
	public double getTotalPricae() {
		return totalPricae;
	}
	public void setTotalPricae(double totalPricae) {
		this.totalPricae = totalPricae;
	}
	public int getAddressId() {
		return addressId;
	}
	public void setAddressId(int addressId) {
		this.addressId = addressId;
	}
	
}
